<template>
  <div class="app-container">
    <el-container class="with-aside">
      <!-- 左侧筛选 -->
      <el-aside width="220px" class="facet-aside">
        <!-- 项目级别 -->
        <div class="facet-block">
          <div class="facet-title">项目级别</div>
          <ul class="facet-list">
            <li :class="{ active: facet.level === null }" @click="selectFacet('level', null)">全部</li>
            <li v-for="opt in levelOptions" :key="opt.value" :class="{ active: facet.level === opt.value }"
              @click="selectFacet('level', opt.value)">
              {{ opt.label }}
            </li>
          </ul>
        </div>

        <!-- 立项年份 -->
        <div class="facet-block">
          <div class="facet-title">立项年份</div>
          <ul class="facet-list">
            <li :class="{ active: facet.year === null }" @click="selectFacet('year', null)">全部</li>
            <li v-for="y in yearOptions" :key="y" :class="{ active: facet.year === y }" @click="selectFacet('year', y)">
              {{ y }}
            </li>
          </ul>
        </div>

        <!-- 状态 -->
        <div class="facet-block">
          <div class="facet-title">状态</div>
          <ul class="facet-list">
            <li :class="{ active: facet.status === null }" @click="selectFacet('status', null)">全部</li>
            <li v-for="d in dict.type.project_status" :key="d.value" :class="{ active: facet.status === d.value }"
              @click="selectFacet('status', d.value)">
              {{ d.label }}
            </li>
          </ul>
        </div>
      </el-aside>

      <!-- 右侧主内容 -->
      <el-main>
        <!-- 顶部搜索：去掉项目级别/立项时间/状态 -->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
          label-width="120px">
          <el-form-item label="委托方合同编号:" prop="projectCode">
            <el-input v-model="queryParams.projectCode" placeholder="请输入委托方合同编号" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="项目名称:" prop="projectName">
            <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="委托方单位:" prop="entrustOrg">
            <el-input v-model="queryParams.entrustOrg" placeholder="请输入委托方单位" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['project:project:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['project:project:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['project:project:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['project:project:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <!-- 序号列 -->
          <el-table-column type="index" label="序号" width="50" align="center" />
          <el-table-column label="委托方合同编号编号" align="center" prop="projectCode" />
          <el-table-column label="项目名称" align="center" prop="projectName" />
          <el-table-column label="项目级别" align="center" prop="projectLevel" />
          <el-table-column label="项目分类" align="center" prop="projectType" />
          <el-table-column label="委托方单位" align="center" prop="entrustOrg" />
          <el-table-column label="总额经费（含税、万元）" align="center" prop="fundingAmount" />
          <el-table-column label="立项日期" align="center" prop="startDate" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.project_status" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-view" @click="handleList(scope.row)">查看项目详情</el-button>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['project:project:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-view"
                @click="handleDocList(scope.row)">所属项目文档</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['project:project:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-main>
    </el-container>


    <!-- 添加或修改模态框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="custom-form">
        <!-- 使用 el-row 和 el-col 来布局输入框 -->

        <el-row :gutter="20">
          <!-- 委托方合同编号 -->
          <el-col :span="12">
            <el-form-item label="委托方合同编号" prop="projectCode">
              <el-input v-model="form.projectCode" placeholder="请输入委托方合同编号" />
            </el-form-item>
          </el-col>

          <!-- 项目名称 -->
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 项目级别 -->
          <el-col :span="12">
            <el-form-item label="项目级别" prop="projectLevel">
              <el-select v-model="form.projectLevel" placeholder="请选择项目级别">
                <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 项目分类 -->
          <el-col :span="12">
            <el-form-item label="项目分类" prop="projectType">
              <el-input v-model="form.projectType" placeholder="请输入项目分类" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 委托方单位 -->
          <el-col :span="12">
            <el-form-item label="委托方单位" prop="entrustOrg">
              <el-input v-model="form.entrustOrg" placeholder="请输入委托方单位" />
            </el-form-item>
          </el-col>

          <!-- 合作经费 -->
          <el-col :span="12">
            <el-form-item label="合作经费（万元）" prop="fundingTeamwork">
              <el-input v-model="form.fundingTeamwork" placeholder="请输入合作经费（万元）" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 总额经费 -->
          <el-col :span="12">
            <el-form-item label="总额经费（含税、万元）" prop="fundingAmount">
              <el-input v-model="form.fundingAmount" placeholder="请输入总额经费（含税、万元）" />
            </el-form-item>
          </el-col>

          <!-- 立项日期 -->
          <el-col :span="12">
            <el-form-item label="立项日期" prop="startDate">
              <el-date-picker v-model="form.startDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择立项日期" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 计划结项日期 -->
          <el-col :span="12">
            <el-form-item label="计划结项日期" prop="endDate">
              <el-date-picker v-model="form.endDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择计划结项日期" />
            </el-form-item>
          </el-col>

          <!-- 要求论文数量 -->
          <el-col :span="12">
            <el-form-item label="要求论文数量" prop="reqPaperCount">
              <el-input v-model="form.reqPaperCount" placeholder="请输入要求论文数量" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 要求专利数量 -->
          <el-col :span="12">
            <el-form-item label="要求专利数量" prop="reqPatentCount">
              <el-input v-model="form.reqPatentCount" placeholder="请输入要求专利数量" />
            </el-form-item>
          </el-col>

          <!-- 要求会议数量 -->
          <el-col :span="12">
            <el-form-item label="要求会议数量" prop="reqMeetingCount">
              <el-input v-model="form.reqMeetingCount" placeholder="请输入要求会议数量" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 要求培养人才数量 -->
          <el-col :span="12">
            <el-form-item label="要求培养人才数量" prop="reqTalentCount">
              <el-input v-model="form.reqTalentCount" placeholder="请输入要求培养人才数量" />
            </el-form-item>
          </el-col>

          <!-- 要求获奖数量 -->
          <el-col :span="12">
            <el-form-item label="要求获奖数量" prop="reqAwardCount">
              <el-input v-model="form.reqAwardCount" placeholder="请输入要求获奖数量" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 要求软著数量 -->
          <el-col :span="12">
            <el-form-item label="要求软著数量" prop="reqSoftCount">
              <el-input v-model="form.reqSoftCount" placeholder="请输入要求软著数量" />
            </el-form-item>
          </el-col>

          <!-- 所属专业 -->
          <el-col :span="12">
            <el-form-item label="所属专业" prop="belongto">
              <el-select v-model="form.belongto" placeholder="请选择所属专业">
                <el-option v-for="item in belongtoList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 状态 -->
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 负责人 -->
          <el-col :span="12">
            <el-form-item label="负责人姓名" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人姓名" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="成员" prop="member">
              <div v-for="(member, index) in form.member" :key="index" class="member-item">
                <el-input v-model="form.member[index]" placeholder="请输入成员姓名" />
                <el-button type="danger" icon="el-icon-delete" @click="removeMember(index)" size="mini"
                  style="margin-left: 10px;">删除</el-button>
              </div>
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="addMember">添加成员</el-button>
            </el-form-item>
          </el-col>
        </el-row>



      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>

    <!-- 项目文档对话框 -->
    <el-dialog title="所属项目文档" :visible.sync="openDoc" width="900px" append-to-body>
      <!-- 顶部：项目信息摘要 -->
      <el-card shadow="never" class="box-card">
        <div slot="header" class="clearfix">
          <span class="card-title">项目信息</span>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <span class="detail-label">项目名称：</span>
              <span class="detail-value">{{ viewForm.projectName || '-' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <span class="detail-label">负责人：</span>
              <span class="detail-value">{{ viewForm.leader || '-' }}</span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-item">
              <span class="detail-label">总额经费(万元)：</span>
              <span class="detail-value">{{ viewForm.fundingAmount || '-' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <span class="detail-label">合作经费(万元)：</span>
              <span class="detail-value">{{ viewForm.fundingTeamwork || '-' }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 文档列表 -->
      <el-card shadow="never" class="box-card" style="margin-top: 16px;">
        <div slot="header" class="clearfix">
          <span class="card-title">文档列表（{{ docTotal }}）</span>
        </div>

        <el-table :data="docList" v-loading="docLoading" style="width: 100%;">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <!-- 下面这些字段名请根据你的后端返回替换；已给出常见命名做兜底 -->
          <el-table-column label="文档名称" prop="name">
            <template slot-scope="scope">
              {{ scope.row.fileName || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="类型" width="120" prop="type">
            <template slot-scope="scope">
              {{ scope.row.fileType || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="上传时间" width="180" prop="createTime">
            <template slot-scope="scope">
              {{ scope.row.uploadTime || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="mini" icon="el-icon-download" @click="downLoadDoc(scope.row)">下载</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <div slot="footer" class="dialog-footer">
        <el-button @click="openDoc = false">关闭</el-button>
      </div>
    </el-dialog>


    <!-- 查看详情对话框 -->
    <el-dialog title="项目详情" :visible.sync="openView" width="800px" append-to-body>
      <el-scrollbar style="height: 500px;">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="card-title">基础信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">委托方合同编号：</span>
                <span class="detail-value">{{ viewForm.projectCode || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">项目名称：</span>
                <span class="detail-value">{{ viewForm.projectName || '-' }}</span>
              </div>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">项目级别：</span>
                <span class="detail-value">{{ viewForm.projectLevel || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">项目分类：</span>
                <span class="detail-value">{{ viewForm.projectType || '-' }}</span>
              </div>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">委托方单位：</span>
                <span class="detail-value">{{ viewForm.entrustOrg || '-' }}</span>
              </div>
            </el-col>

            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">合作经费(万元)：</span>
                <span class="detail-value">{{ viewForm.fundingTeamwork || '-' }}</span>
              </div>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">总额经费(含税、万元)：</span>
                <span class="detail-value">{{ viewForm.fundingAmount || '-' }}</span>
              </div>
            </el-col>

            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">立项日期：</span>
                <span class="detail-value">
                  {{ viewForm.startDate ? parseTime(viewForm.startDate, '{y}-{m}-{d}') : '-' }}
                </span>
              </div>
            </el-col>

          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">状态：</span>
                <span class="detail-value">
                  <dict-tag :options="dict.type.project_status" :value="viewForm.status" />
                </span>
              </div>
            </el-col>

            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">所属专业：</span>
                <span class="detail-value">{{ viewForm.belongto || '-' }}</span>
              </div>
            </el-col>
          </el-row>


        </el-card>

        <el-card class="box-card" shadow="never" style="margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span class="card-title">任务要求</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">要求论文数量：</span>
                <span class="detail-value">{{ viewForm.reqPaperCount || '0' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">要求专利数量：</span>
                <span class="detail-value">{{ viewForm.reqPatentCount || '0' }}</span>
              </div>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">要求会议数量：</span>
                <span class="detail-value">{{ viewForm.reqMeetingCount || '0' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">培养人才数量：</span>
                <span class="detail-value">{{ viewForm.reqTalentCount || '0' }}</span>
              </div>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">要求获奖数量：</span>
                <span class="detail-value">{{ viewForm.reqAwardCount || '0' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">要求软著数量：</span>
                <span class="detail-value">{{ viewForm.reqSoftCount || '0' }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <el-card class="box-card" shadow="never" style="margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span class="card-title">其他信息</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">备注：</span>
            <div class="detail-value pre-line">{{ viewForm.remark || '-' }}</div>
          </div>
        </el-card>

        <el-card class="box-card" shadow="never" style="margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span class="card-title">成员信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">负责人：</span>
                <span class="detail-value">{{ viewForm.leader || '-' }}</span>
              </div>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="20">
              <div class="detail-item">
                <span class="detail-label">项目成员：</span>

                <el-table :data="viewForm.member" style="width: 100%">
                  <el-table-column label="序号" type="index" width="80"></el-table-column>

                  <el-table-column label="成员名称">
                    <template slot-scope="scope">
                      {{ scope.row.nickName || '-' }}
                    </template>
                  </el-table-column>

                  <el-table-column label="工号/学号">
                    <template slot-scope="scope">
                      {{ scope.row.userName || '-' }}
                    </template>
                  </el-table-column>

                </el-table>
              </div>
            </el-col>
          </el-row>
        </el-card>

      </el-scrollbar>



      <div slot="footer" class="dialog-footer">
        <el-button @click="openView = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProject, getProject, delProject, addProject, updateProject } from "@/api/project/project";
import { listDoc } from "@/api/project/doc"

export default {
  name: "Project",
  dicts: ["project_status"],
  data() {
    return {


      belongtoList: [{
        value: '测控',
        label: '测控'
      }, {
        value: '控压',
        label: '控压'
      }, {
        value: '机械',
        label: '机械'
      }, {
        value: '完整性',
        label: '完整性'
      }, {
        value: '其它',
        label: '其它'
      }],

      statusList: [{
        value: 0,
        label: '进行中'
      }, {
        value: 1,
        label: '已完成'
      }, {
        value: 2,
        label: '未完成'
      }],
      // 项目文档表格数据
      docList: [],

      openView: false, // 查看详情对话框控制变量
      viewForm: {}, // 查看详情表单数据

      openDoc: false,     // 项目文档对话框开关
      docLoading: false,  // 文档表格 loading

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //文件总条数
      docTotal: 0,
      // 项目管理表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 左侧筛选选择状态
      facet: {
        level: null, // 项目级别
        year: null, // 立项年份
        status: null // 状态
      },

      // 左侧“项目级别”选项（如果你有字典可替换为后端返回）
      levelOptions: [
        { label: "国家级", value: "国家级" },
        { label: "省部级", value: "省部级" },
        { label: "市厅级", value: "市厅级" },
        { label: "校级", value: "校级" },
        { label: "企业委托", value: "企业委托" }
      ],

      // 左侧“立项年份”——默认当前年起向前5年
      yearOptions: [],

      // 旧的范围选择保留用于请求参数拼装（不在UI展示）
      daterangeStartDate: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectCode: null,
        projectName: null,
        projectLevel: null,
        projectType: null,
        entrustOrg: null,
        startDate: null,
        status: null
      },
      //用于查询项目文件的参数
      queryDocParams: {
        pageNum: 1,
        pageSize: 1000,
        projectId: null,
      },

      // 表单参数
      form: {     // 成员数组，存储成员的姓名
        member: []
      },
      // 表单校验
      rules: {
        projectCode: [{ required: true, message: "委托方合同编号不能为空", trigger: "blur" }],
        projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
        projectLevel: [{ required: true, message: "项目级别不能为空", trigger: "blur" }],
        projectType: [{ required: true, message: "项目分类不能为空", trigger: "change" }],
        entrustOrg: [{ required: true, message: "委托方单位不能为空", trigger: "blur" }],
        fundingTeamwork: [{ required: true, message: "合作经费不能为空", trigger: "blur" }],
        fundingAmount: [{ required: true, message: "总额经费不能为空", trigger: "blur" }],
        startDate: [{ required: true, message: "立项日期不能为空", trigger: "blur" }],
        endDate: [{ required: true, message: "计划结项日期不能为空", trigger: "blur" }],
        reqPaperCount: [{ required: true, message: "要求论文数量不能为空", trigger: "blur" }],
        reqPatentCount: [{ required: true, message: "要求专利数量不能为空", trigger: "blur" }],
        reqMeetingCount: [{ required: true, message: "要求会议数量不能为空", trigger: "blur" }],
        reqTalentCount: [{ required: true, message: "要求培养人才数量不能为空", trigger: "blur" }],
        reqAwardCount: [{ required: true, message: "要求获奖数量不能为空", trigger: "blur" }],
        reqSoftCount: [{ required: true, message: "要求软著数量不能为空", trigger: "blur" }],
        belongto: [{ required: true, message: "所属专业不能为空", trigger: "blur" }],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }]
      }
    };
  },


  created() {
    this.buildYearOptions();
    this.getList();
  },
  methods: {
    downLoadDoc(row) {
      const url = row.url || row.previewUrl || row.fileUrl;
      if (url) {
        window.open(url, '_blank');
      } else {
        this.$modal.msgWarning('未找到可预览的链接');
      }
    },
    /** 生成年份可选项（当前年起往前5年） */
    buildYearOptions() {
      const now = new Date().getFullYear();
      const years = [];
      for (let i = 0; i < 5; i++) years.push(now - i);
      this.yearOptions = years;
    },
    // 添加成员
    addMember() {
      if (!this.form.member) {
        this.$set(this.form, 'member', []); // 确保 form.member 存在且为数组
      }
      this.form.member.push('');  // 直接向数组添加一个空的字符串，表示成员姓名
      console.log(this.form.member);  // 输出成员数组的当前状态
    },

    removeMember(index) {
      if (this.form.member && this.form.member.length > 0) {
        this.form.member.splice(index, 1);  // 从数组中删除指定索引的成员
      }
    },
    /** 左侧筛选点击 */
    selectFacet(type, value) {
      this.facet[type] = value;

      if (type === "level") {
        this.queryParams.projectLevel = value || null;
      }

      if (type === "status") {
        this.queryParams.status = value || null;
      }

      if (type === "year") {
        if (value) {
          // 年份 -> 年度起止
          this.daterangeStartDate = [`${value}-01-01`, `${value}-12-31`];
        } else {
          this.daterangeStartDate = [];
        }
      }

      this.handleQuery();
    },

    /** 查询项目管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (this.daterangeStartDate && this.daterangeStartDate.length === 2) {
        this.queryParams.params["beginStartDate"] = this.daterangeStartDate[0];
        this.queryParams.params["endStartDate"] = this.daterangeStartDate[1];
      }
      listProject(this.queryParams).then((response) => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectCode: null,
        projectName: null,
        projectLevel: null,
        projectType: null,
        entrustOrg: null,
        fundingTeamwork: null,
        fundingAmount: null,
        startDate: null,
        endDate: null,
        reqPaperCount: null,
        reqPatentCount: null,
        reqMeetingCount: null,
        reqTalentCount: null,
        reqAwardCount: null,
        reqSoftCount: null,
        belongto: null,
        status: null,
        leader: null,
        remark: null,
        createdBy: null,
        updatedBy: null,
        createdAt: null,
        updatedAt: null,
        member: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作（同时清空左侧筛选） */
    resetQuery() {
      this.facet = { level: null, year: null, status: null };
      this.daterangeStartDate = [];
      this.resetForm("queryForm");
      this.queryParams.projectLevel = null;
      this.queryParams.status = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目管理";
    },
    /**
     * 查看详情操作
     */
    handleList(row) {
      const id = row.id;
      getProject(id).then((response) => {
        this.viewForm = response.data;
        this.openView = true;
      });
    },

    // 获取项目所属文档列表，同时显示部分项目信息
    handleDocList(row) {
      const id = row.id;
      this.openDoc = true;      // 先打开对话框，用户有反馈
      this.docLoading = true;

      // 记录当前项目 ID 供查询
      this.queryDocParams.projectId = id;

      // 并行请求：项目信息 + 文档列表
      Promise.all([
        getProject(id),
        listDoc(this.queryDocParams)
      ])
        .then(([projRes, docRes]) => {
          this.viewForm = projRes.data || {};
          this.docList = (docRes && docRes.rows) || [];
          this.docTotal = (docRes && docRes.total) || 0;
        })
        .finally(() => {
          this.docLoading = false;
        });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = (row && row.id) || this.ids;

      getProject(id).then((response) => {
        const data = response.data || {};

        // 后端返回的 member 可能是对象数组，转成姓名字符串数组供表单编辑使用
        const membersRaw = Array.isArray(data.member) ? data.member : [];
        const memberNames = membersRaw
          .map(m => {
            if (typeof m === 'string') return m.trim();
            // 兜底优先级：nickName > name > userName
            return (m && (m.nickName || m.name || m.userName)) || '';
          })
          .filter(Boolean);

        // 将表单中的 member 设为姓名数组
        this.form = {
          ...data,
          member: memberNames
        };

        this.open = true;
        this.title = "修改项目管理";
      });
    },

    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 处理member，确保它是一个简单的字符串数组
          if (Array.isArray(this.form.member)) {
            this.form.member = this.form.member.filter(member => typeof member === 'string' && member.trim() !== '');
          }

          if (this.form.id != null) {
            updateProject(this.form).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProject(this.form).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = (row && row.id) || this.ids;
      this.$modal
        .confirm('是否确认删除项目管理编号为"' + ids + '"的数据项？')
        .then(function () {
          return delProject(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "project/project/export",
        {
          ...this.queryParams
        },
        `project_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>

<style scoped>
/* ---- 左侧筛选样式 ---- */
.with-aside {
  background: #fff;
}

.facet-aside {
  border-right: 1px solid #ebeef5;
  padding: 12px 10px;
}

.facet-block+.facet-block {
  margin-top: 16px;
}

.facet-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.facet-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.facet-list li {
  line-height: 28px;
  padding: 0 8px;
  border-radius: 4px;
  cursor: pointer;
  color: #606266;
}

.facet-list li:hover {
  background: #f5f7fa;
}

.facet-list li.active {
  background: #ecf5ff;
  color: #409eff;
  font-weight: 600;
}

/* ---- 原有样式（保留） ---- */
.box-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.box-card>>>.el-card__header {
  background-color: #f5f7fa;
  padding: 12px 20px;
  border-bottom: 1px solid #ebeef5;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  min-height: 24px;
  line-height: 24px;
}

.detail-label {
  width: 120px;
  color: #909399;
  font-weight: 500;
  text-align: right;
  margin-right: 10px;
  flex-shrink: 0;
}

.detail-value {
  flex: 1;
  color: #606266;
  word-break: break-all;
}

.detail-value.pre-line {
  white-space: pre-line;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.dialog-footer {
  text-align: right;
  padding-top: 10px;
}

.el-dialog__body {
  padding: 15px 20px;
}

.el-scrollbar__wrap {
  overflow-x: hidden;
}

/* 右上角按钮区的小间距 */
.mb8 {
  margin-bottom: 8px;
}

.member-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
</style>
